﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

namespace MSAS.DIP.Common
{
    public static class UnityExtensions
    {
        /// <summary>
        /// Get all the names from the container that are used to disambiguate multiple
        /// registrations of type T
        /// </summary>
        /// <typeparam name="T">Type that has been registered in the container</typeparam>
        /// <param name="container">IUnityContainer that has at least one registered component of type T</param>
        /// <returns></returns>
        public static List<string> ResolveRegisteredNames<T>(this IUnityContainer container)
        {
            // use reflection to get access to the registeredNames field
            object names = container.GetType().InvokeMember(
                "registeredNames",
                System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.NonPublic |
                System.Reflection.BindingFlags.GetField,
                null,
                container,
                null);

            // get a list of all names associated with each type in the unity container
            Dictionary<Type, List<string>> keys = names.GetType().InvokeMember(
                "registeredKeys",
                System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.NonPublic |
                System.Reflection.BindingFlags.Instance,
                null,
                names,
                null) as Dictionary<Type, List<string>>;
            
            // return all the names associated with type T
            return keys[typeof(T)];
        }
    }
}
